package org.migrantalks;

import io.vertx.config.ConfigRetriever;
import io.vertx.core.*;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import io.vertx.core.shareddata.LocalMap;
import io.vertx.core.shareddata.SharedData;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.CorsHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.migrantalks.base.Result;
import org.migrantalks.service.IUserService;
import org.migrantalks.service.impl.UserService;

import java.util.HashSet;
import java.util.Set;

@Slf4j
public class AppLauncher extends AbstractVerticle {

    private int port;
    private static final String CONTENT_TYPE_JSON = "application/json;charset=utf-8";
    private static String env = "dev";

    private IUserService userService;

    private void initData() {
        userService = new UserService();
    }

    @Override
    public void start(Promise<Void> promise) throws Exception {
        initData();

        Router router = Router.router(vertx);

        // CORS support
        Set<String> allowHeaders = new HashSet<>();
        allowHeaders.add("x-requested-with");
        allowHeaders.add("Access-Control-Allow-Origin");
        allowHeaders.add("origin");
        allowHeaders.add("Content-Type");
        allowHeaders.add("accept");
        Set<HttpMethod> allowMethods = new HashSet<>();
        allowMethods.add(HttpMethod.GET);
        allowMethods.add(HttpMethod.POST);
        allowMethods.add(HttpMethod.DELETE);
        allowMethods.add(HttpMethod.PATCH);

        router.route().handler(BodyHandler.create());
        router.route().handler(CorsHandler.create("*")
                .allowedHeaders(allowHeaders)
                .allowedMethods(allowMethods));

        // 加载 config.json 配置文件
        ConfigRetriever retriever = ConfigRetriever.create(vertx);

        retriever.getConfig(ar -> {

            //vertx.close();
            JsonObject result = ar.result();

            // 默认读取dev开发环境配置
            JsonObject envConfig = result.getJsonObject(env);

            JsonObject serverConfig = envConfig.getJsonObject("server");
            this.port = serverConfig.getInteger("port");

            // 配置保存在共享数据中
            SharedData sharedData = vertx.sharedData();
            LocalMap<String, Object> localMap = sharedData.getLocalMap("mvertx");
            localMap.put("env", env);
            localMap.put("envConfig", envConfig);

        });

        router.get("/").handler(ctx -> {

            HttpServerResponse response = ctx.response();
            response.putHeader("content-type", "text/plain");

            response.end("Hello World from Vert.x-Web!");
        });


        // get请求
        /*
        router.get("/hi")
                .respond(ctx -> Future.succeededFuture(new JsonObject().put("Hello", "Vert.x")));

        // 模板引擎
        ThymeleafTemplateEngine templateEngine = ThymeleafTemplateEngine.create(vertx);
        router.get("/hello").handler(ctx -> {

            Map<String, Object> msg = new HashMap<>();
            msg.put("msg", "Hello Thymeleaf!");

            templateEngine.render(msg, "templates/hello.html", res -> {
                if (res.succeeded()) {
                    ctx.response().putHeader("Content-Type", "text/html").end(res.result());
                } else {
                    ctx.fail(res.cause());
                }
            });
        });*/


        // 数据库
        router.post("/login/v2").handler(ctx -> {

            HttpServerResponse response = ctx.response();
            response.putHeader("Content-Type", CONTENT_TYPE_JSON);

            String userName = ctx.request().getParam("userName");
            String password = ctx.request().getParam("password");

            userService.login(response, userName, password);
        });

        router.get("/user").handler(ctx -> {

            HttpServerResponse response = ctx.response();
            response.putHeader("Content-Type", CONTENT_TYPE_JSON);

            userService.getUserList(response);
        });

        router.get("/user/:id").handler(ctx -> {

            HttpServerResponse response = ctx.response();
            response.putHeader("Content-Type", CONTENT_TYPE_JSON);

            String userId = ctx.request().getParam("id");
            if (StringUtils.isBlank(userId)) {
                response.end(Json.encodePrettily(Result.fail("用户id不可为空")));
            }

            userService.getUserById(response, userId);
        });

        /*router.get("/auth").handler(ctx -> {
            IUserService.auth(vertx, ctx);
        });*/

        vertx.createHttpServer()
                .requestHandler(router)
                .listen(port, http -> {
                    if (http.succeeded()) {

                        log.info("HTTP Server is listening on {}", port);
                        promise.complete();

                    } else {

                        log.error("Failed to run HTTP Server", http.cause());
                        promise.fail(http.cause());
                    }
                });
    }

    public static void main(String[] args) {

        Vertx.vertx().deployVerticle(new AppLauncher());
        log.info("Deploy Verticle....");
    }

}
